#include <iostream>
#include "Usage.hpp"
#include "Httpserver.hpp"
#include "Util.hpp"
#include <fstream>

#define ROOT "./wwwroot"
#define HOMEPAGE "/index.html"

void HandlerHttpRequest(int sockfd)
{
    char buffer[10240];
    ssize_t s = recv(sockfd,buffer,sizeof(buffer)-1,0);
    if(s > 0)
    {
        buffer[s] = 0;
        std::cout << buffer << "-------------------\n" <<std::endl;
    }

    std::vector<std::string> v;
    Util::cutString(buffer,"\r\n",&v);

    std::vector<std::string> vblock;
    Util::cutString(v[0]," ",&vblock);

    std::string file = vblock[1];
    std::string target   = ROOT;
    target += file;
    // std::cout << target << std::endl;

    std::string content;
    std::ifstream in(target);
    if(in.is_open())
    {
        std::string line;
        while(std::getline(in,line))
        {
            content += line;
        }
        in.close();
    }

    std::string HttpResponse;
    if(content.empty())
    {
        HttpResponse = "Http/1.1 302 found\r\n";
        HttpResponse += "Location: http://www.qq.com/\r\n";
    }
    else
    {
        HttpResponse = "HTTP/1.1 200 OK\r\n";
        HttpResponse += ("Content-Type: text/html\r\n"); 
        HttpResponse += ("Content-Length: " + std::to_string(content.size()) + "\r\n");
        HttpResponse += "Set-Cookie: 这是一个cookie\r\n";
    }
    // for(auto& iter : vblock)
    // {
    //     std::cout<< iter << std::endl;
    // }
    // std::cout << std::endl;
    //试着构建一个http的响应
    HttpResponse += "\r\n";
    HttpResponse += content;
    send(sockfd,HttpResponse.c_str(),HttpResponse.size(),0);
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::unique_ptr<Httpserver> httpserver (new Httpserver(atoi(argv[1]),HandlerHttpRequest));
    httpserver->Start();
    return 0;
}